<script lang="ts" setup>
import { Plus, InfoFilled } from '@element-plus/icons-vue';
import { UiCellBtns, openModal, RULE_HELP, isEmpty, treeUtil, throwError, paramSourceSelect } from '../../../utils';
import { ServiceParamConfig, TableCellBtn, Required, RequestParamConfig } from '../../../utils/types';
import { useParamConfig } from '../utils';
import { ref } from 'vue';
import { apiAuth } from '../../../api';

const cls = 'ui-api-editor-service-param-config'

const props = defineProps<{
  isTree?: boolean,
  optionValue: RequestParamConfig[],
  modelValue: ServiceParamConfig[]
}>()

const { addItem, addSubItem, removeItem, disableType, canAddChild, dataTypes, apiEditor } = useParamConfig(props)
const formData = apiEditor.getForm()
const getBtns = (row: any, index: number) => {
  return [
    canAddChild(row) && { label: '添加', onClick: addSubItem.bind(null, row) },
    { label: '删除', onClick: removeItem.bind(null, row) },
    !isEmpty(row.source) && { label: '入参配置', onClick: configItem.bind(null, row, index) }
  ] as TableCellBtn[]
}
const apiAuthId = ref< string >()
const getApiAuthId=( _ )=>{
  if( _ ==='2'){
    apiAuth.getAuthId({
      apiId: apiEditor.getForm().apiId,
      versionId: apiEditor.getForm().versionId
    }).then(res => {
      apiAuthId.value = res.data
    })
  }
}

const configItem =  (row: ServiceParamConfig, index: number) => {
  let optionValue = [ ...props.optionValue ]
  if(row.source==='0'){
    if(props.isTree){
      const parNode = treeUtil.findParent({
        data: props.modelValue,
        config: { key: '_k', children: 'childrenApiParams' },
        node: row
      })
      if(parNode){
        const requstParNode = treeUtil.find({
          data: props.optionValue,
          callback: node => node.id === parNode.sourceValue
        })
        if ( !requstParNode || requstParNode.childrenApiParams.length < 0 ) {
          return throwError('此节点没有前段映射')
        }
          optionValue= requstParNode.childrenApiParams.filter( _ =>{
          return parNode.childrenApiParams.find( v => {
            return v.param !== _.param
          })
        })
      }
    }  
  }
  const comp = (() => {
    switch (row.source) {
      case '0':
        return () => import('../RequstParamsDialog.vue')
      case '2':
        return () => import('../AuthenticationPluginConfig.vue')
      case '3':
        return () => import('../SystemParameterDialog.vue')
    }
  })()
  if (comp) {
    openModal(comp, {
      ...(row.source === '2' ? { size: 800 } : { width: '350px'}),
      row: { row, optionValue, apiAuthId: apiAuthId.value, isTree: props.isTree, formData: formData.value },
      onSubmitted: params => {
        if(row.source!=='2'){
          if(props.isTree){
            const parNode = treeUtil.findParent({
              data: props.modelValue,
              config: { key: '_k', children: 'childrenApiParams' },
              node: row
            })
            const childs = parNode ? parNode.childrenApiParams : props.modelValue
            const indx = childs.findIndex(_=>{
              return _._k === row._k
            })
            childs[indx] = {...row, ...params.form}
          }else{
            props.modelValue[index] = {...row, ...params.form}
          }
        }
      }
    })
  }
}

</script>

<template>
  <div :class="cls">
    <ElTable :data="props.modelValue" row-key="_k" default-expand-all :tree-props="{ children: 'childrenApiParams' }">
      <ElTableColumn min-width="180">
        <template #header>
          <span class="star">*</span>后端参数名
        </template>
        <template v-slot="{ row }">
          <ElInput v-model="row.param" :disabled="row.source==='0'" placeholder="请输入" />
        </template>
      </ElTableColumn>
      <ElTableColumn min-width="120">
        <template #header>
          <span class="star">*</span>后端参数类型
        </template>
        <template v-slot="{ row }">
          <ElSelect v-model="row.paramType" :disabled="row.source === '0' || disableType(row)">
            <ElOption v-for="_ in dataTypes" :key="_.value" v-bind="_" />
          </ElSelect>
        </template>
      </ElTableColumn>
      <ElTableColumn label="校验规则" min-width="120">
        <template #header>
          <div :class="`${cls}_title`">
            <span :class="`${cls}_title-text`">校验规则</span>
            <ElTooltip
              effect="light"
              placement="right"
              :popper-class="`${cls}_popper`"
              :content="RULE_HELP">
              <ElIcon>
                <InfoFilled />
              </ElIcon>
            </ElTooltip>
          </div>
        </template>
        <template v-slot="{ row }">
          <ElInput v-model ="row.paramRule" :disabled="row.source==='0'" placeholder="请输入" />
        </template>
      </ElTableColumn>
      <ElTableColumn label="必填" width="60">
        <template v-slot="{ row }">
          <ElCheckbox v-model="row.isRequired" :true-value="Required.YES" :false-value="Required.NO" :disabled="row.source==='0'"/>
        </template>
      </ElTableColumn>
      <ElTableColumn label="对应入参来源" min-width="160">
        <template v-slot="{ row }">
          <ElSelect v-model="row.source" :disabled="row.source==='2'" @change="getApiAuthId">
            <ElOption value="0" label="前端请求映射" />
            <ElOption value="2" label="鉴权插件" :disabled ="!!apiAuthId"/>
            <ElOption value="3" label="系统参数" :disabled ="!apiAuthId "/>
          </ElSelect>
        </template>
      </ElTableColumn>
      <ElTableColumn label="操作" width="160" fixed="right">
        <template v-slot="{ row , $index}">
          <UiCellBtns :btns="getBtns(row, $index)" />
        </template>
      </ElTableColumn>
    </ElTable>
    <div :class="`${cls}_actions`">
      <ElButton :icon="Plus" type="primary" plain @click="addItem">添加一行</ElButton>
    </div>
  </div>
</template>

<style lang="scss">
.ui-api-editor-service-param-config {
  &_actions {
    width: 100%;
    margin-top: $page-padding;
    text-align: center;
  }
  &_title {
    display: flex;
    align-items: center;
    &-text {
      margin-right: 3px;
    }
  }
  &_popper {
    max-width: 340px;
  }
  .star {
    margin-right: 4px;
    color: var(--el-color-danger);
  }
}
</style>
